package com.tuanzi.loan.web.bean.family;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.constants.DictionaryCode;
import com.tuanzi.loan.business.entity.common.CommProductId;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.service.family.SwitchService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.family.SwitchListSearchRequest;
import com.tuanzi.loan.vo.request.family.SwitchRank;
import com.tuanzi.loan.vo.response.family.SwitchListSearchResponse;
import com.tuanzi.loan.web.configuration.JSFListingSessionBean;
import com.tuanzi.loan.web.lazy.family.SwitchListLazyDataModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.faces.bean.ViewScoped;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class SwitchListBean extends JSFListingSessionBean<SwitchListSearchRequest, SwitchListSearchResponse> {

	@Autowired
	private SwitchService switchService;

	@Override
	protected String page() {
		return "/views/family/switch/list.xhtml";
	}

	protected void initLazyDataModel() {
		$ = new SwitchListSearchRequest();

		HashMap<String, SwitchRank> switchRankMap = new HashMap<>();
		List<Dictionary> switchModuleDics = dictionaryService.findAllByCode(DictionaryCode.SWITCH_MODULE);
		for (Dictionary dic : switchModuleDics) {
			switchRankMap.put(dic.getValue1(), new SwitchRank(dic.getValue1()));
		}
		dictionaryService.findAllByCode(DictionaryCode.SWITCH_NAME).stream().collect(Collectors.groupingBy(Dictionary::getValue2)).forEach((moduleId, dics) -> {
			SwitchRank switchRank = switchRankMap.get(moduleId);
			switchRank.members = dics.stream().map(Dictionary::getValue1).collect(Collectors.toList());
		});

		lazyDataModel = new SwitchListLazyDataModel($, session, switchRankMap, switchService);
	}

	public String onEdit(String id) {
		return redirect("/views/family/switch/info.xhtml?id=" + id);
	}

	public void onReset() {
		initLazyDataModel();
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(DictionaryCode.LARGE_COMMON_PRODUCT, DictionaryCode.SWITCH_MODULE, DictionaryCode.SWITCH_NAME);
	}

	public String convertToProductNames(List<Integer> productIds) {
		List<CommProductId> commProductIds = getCommProductIds();
		Map<Integer, CommProductId> commProductIdMap = commProductIds.stream().collect(Collectors.toMap(CommProductId::getProductId, commProductId -> commProductId));
		List<String> productNames = productIds.stream().map(productId -> commProductIdMap.get(productId).getName()).collect(Collectors.toList());
		return StringUtils.join(productNames, '、');
	}
}
